// 学生成绩管理

const tbody = document.querySelector('tbody')

// 初始化成绩
function initScore() {
  axios({
    url: '/score/list',
    method: 'GET'
  }).then(({ data: res }) => {
    if (res.code === 0) {
      const arr = []
      for (let k in res.data) {
        arr.push(`
        <tr>
            <th scope="row">${ k }</th>
            <td>${ res.data[k].name }</td>
            <td class="score" data-id="${ k }" data-batch="1">${ res.data[k].score[0] }</td>
            <td class="score" data-id="${ k }" data-batch="2">${ res.data[k].score[1] }</td>
            <td class="score" data-id="${ k }" data-batch="3">${ res.data[k].score[2] }</td>
            <td class="score" data-id="${ k }" data-batch="4">${ res.data[k].score[3] }</td>
            <td class="score" data-id="${ k }" data-batch="5">${ res.data[k].score[4] }</td>
        </tr>
        `)
      }
      tbody.innerHTML = arr.join('')
    }
  })
}

initScore()

// 修改学员成绩
tbody.addEventListener('dblclick', function (e) {
  const td = e.target
  if (!td.classList.contains('score')) return
  let input = document.createElement('input')
  input.value = td.innerHTML
  td.innerHTML = ''
  td.appendChild(input)
  // 自动获取焦点
  input.focus()
  // 失去焦点恢复原值
  let value = input.value // 备份原值
  input.addEventListener('blur', function () {
    td.innerHTML = value
  })
  
  // 修改成绩
  input.addEventListener('keyup', function (e) {
    if (e.key !== 'Enter') return
    axios({
      url: '/score/entry',
      method: 'POST',
      data: {
        // 获取父节点上的自定义属性this.parentNode.getAttribute
        stu_id: this.parentNode.getAttribute('data-id'),
        batch: this.parentNode.getAttribute('data-batch'),
        score: this.value
      }
    }).then(({ data: res }) => {
      if (res.code === 0) {
        alert(res.message)
        initScore()
      }
    })
  })
})